<template>
  <div class="reminder-config">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常订单处理时限提醒配置</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddRule">
          <el-icon><Plus /></el-icon>新建规则
        </el-button>
      </div>
    </div>

    <!-- 规则列表 -->
    <el-card class="rule-list">
      <el-table
        v-loading="loading"
        :data="ruleList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="type" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reminderType" label="提醒类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getReminderTypeTag(row.reminderType)">
              {{ getReminderTypeLabel(row.reminderType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="timeLimit" label="处理时限" width="120">
          <template #default="{ row }">
            {{ row.timeLimit }}小时
          </template>
        </el-table-column>
        <el-table-column prop="reminderTimes" label="提醒次数" width="100">
          <template #default="{ row }">
            {{ row.reminderTimes }}次
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleCopy(row)">复制</el-button>
            <el-button type="warning" link @click="handlePreview(row)">预览</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 规则编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建规则' : '编辑规则'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="异常类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择异常类型">
            <el-option label="退款纠纷" value="refund" />
            <el-option label="服务投诉" value="complaint" />
            <el-option label="商品问题" value="product" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="提醒类型" prop="reminderType">
          <el-select v-model="form.reminderType" placeholder="请选择提醒类型">
            <el-option label="处理时限提醒" value="time_limit" />
            <el-option label="即将超时提醒" value="approaching" />
            <el-option label="超时提醒" value="overtime" />
            <el-option label="升级提醒" value="escalation" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理时限" prop="timeLimit">
          <el-input-number
            v-model="form.timeLimit"
            :min="1"
            :max="72"
            placeholder="处理时限(小时)"
          />
        </el-form-item>
        <el-form-item label="提醒次数" prop="reminderTimes">
          <el-input-number
            v-model="form.reminderTimes"
            :min="1"
            :max="5"
            placeholder="提醒次数"
          />
        </el-form-item>
        <el-form-item label="提醒间隔" prop="reminderInterval">
          <el-input-number
            v-model="form.reminderInterval"
            :min="1"
            :max="24"
            placeholder="提醒间隔(小时)"
          />
        </el-form-item>
        <el-form-item label="提醒方式" prop="reminderMethods">
          <el-checkbox-group v-model="form.reminderMethods">
            <el-checkbox label="system">系统通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="wechat">微信通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="提醒模板" prop="templates">
          <div class="template-list">
            <div
              v-for="(template, index) in form.templates"
              :key="index"
              class="template-item"
            >
              <div class="template-header">
                <span class="template-title">模板 {{ index + 1 }}</span>
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveTemplate(index)"
                >
                  删除
                </el-button>
              </div>
              <div class="template-content">
                <el-form-item
                  :prop="'templates.' + index + '.method'"
                  :rules="{ required: true, message: '请选择通知方式', trigger: 'change' }"
                >
                  <el-select v-model="template.method" placeholder="通知方式">
                    <el-option label="系统通知" value="system" />
                    <el-option label="短信通知" value="sms" />
                    <el-option label="邮件通知" value="email" />
                    <el-option label="微信通知" value="wechat" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'templates.' + index + '.templateId'"
                  :rules="{ required: true, message: '请选择通知模板', trigger: 'change' }"
                >
                  <el-select
                    v-model="template.templateId"
                    placeholder="通知模板"
                    :disabled="!template.method"
                  >
                    <el-option
                      v-for="tpl in getTemplateList(template.method)"
                      :key="tpl.id"
                      :label="tpl.name"
                      :value="tpl.id"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <div class="template-actions">
              <el-button type="primary" @click="handleAddTemplate">
                <el-icon><Plus /></el-icon>添加模板
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="升级规则" v-if="form.reminderType === 'escalation'">
          <div class="escalation-list">
            <div
              v-for="(rule, index) in form.escalationRules"
              :key="index"
              class="escalation-item"
            >
              <div class="escalation-header">
                <span class="escalation-title">规则 {{ index + 1 }}</span>
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveEscalation(index)"
                >
                  删除
                </el-button>
              </div>
              <div class="escalation-content">
                <el-form-item
                  :prop="'escalationRules.' + index + '.condition'"
                  :rules="{ required: true, message: '请选择升级条件', trigger: 'change' }"
                >
                  <el-select v-model="rule.condition" placeholder="升级条件">
                    <el-option label="超时未处理" value="overtime" />
                    <el-option label="客户投诉" value="complaint" />
                    <el-option label="重复异常" value="repeat" />
                    <el-option label="金额较大" value="amount" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'escalationRules.' + index + '.target'"
                  :rules="{ required: true, message: '请选择升级对象', trigger: 'change' }"
                >
                  <el-select
                    v-model="rule.target"
                    multiple
                    collapse-tags
                    placeholder="升级对象"
                  >
                    <el-option
                      v-for="role in roleList"
                      :key="role.id"
                      :label="role.name"
                      :value="role.id"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <div class="escalation-actions">
              <el-button type="primary" @click="handleAddEscalation">
                <el-icon><Plus /></el-icon>添加规则
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 规则预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="规则预览"
      width="800px"
    >
      <div class="rule-preview">
        <div class="preview-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="规则名称">
              {{ currentRule.name }}
            </el-descriptions-item>
            <el-descriptions-item label="异常类型">
              <el-tag :type="getExceptionTypeTag(currentRule.type)">
                {{ getExceptionTypeLabel(currentRule.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="提醒类型">
              <el-tag :type="getReminderTypeTag(currentRule.reminderType)">
                {{ getReminderTypeLabel(currentRule.reminderType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="处理时限">
              {{ currentRule.timeLimit }}小时
            </el-descriptions-item>
            <el-descriptions-item label="提醒次数">
              {{ currentRule.reminderTimes }}次
            </el-descriptions-item>
            <el-descriptions-item label="提醒间隔">
              {{ currentRule.reminderInterval }}小时
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="preview-section">
          <h3>提醒方式</h3>
          <div class="method-list">
            <el-tag
              v-for="method in currentRule.reminderMethods"
              :key="method"
              :type="getMethodTag(method)"
              class="mx-1"
            >
              {{ getMethodLabel(method) }}
            </el-tag>
          </div>
        </div>
        <div class="preview-section">
          <h3>提醒模板</h3>
          <el-table :data="currentRule.templates" border>
            <el-table-column prop="method" label="通知方式" width="120">
              <template #default="{ row }">
                {{ getMethodLabel(row.method) }}
              </template>
            </el-table-column>
            <el-table-column prop="templateId" label="模板名称" min-width="200">
              <template #default="{ row }">
                {{ getTemplateName(row.method, row.templateId) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="preview-section" v-if="currentRule.reminderType === 'escalation'">
          <h3>升级规则</h3>
          <el-table :data="currentRule.escalationRules" border>
            <el-table-column prop="condition" label="升级条件" width="150">
              <template #default="{ row }">
                {{ getEscalationConditionLabel(row.condition) }}
              </template>
            </el-table-column>
            <el-table-column prop="target" label="升级对象">
              <template #default="{ row }">
                <el-tag
                  v-for="roleId in row.target"
                  :key="roleId"
                  class="mx-1"
                >
                  {{ getRoleName(roleId) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantOrderExceptionReminderRuleList,
  addMerchantOrderExceptionReminderRule,
  updateMerchantOrderExceptionReminderRule,
  deleteMerchantOrderExceptionReminderRule,
  copyMerchantOrderExceptionReminderRule,
  updateMerchantOrderExceptionReminderRuleStatus,
  getMerchantRoleList,
  getMerchantNoticeTemplateList
} from '@/api/merchant'

// 规则列表数据
const loading = ref(false)
const ruleList = ref([])
const roleList = ref([])
const templateList = ref({
  system: [],
  sms: [],
  email: [],
  wechat: []
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: '',
  reminderType: '',
  timeLimit: 24,
  reminderTimes: 3,
  reminderInterval: 4,
  reminderMethods: ['system'],
  templates: [],
  escalationRules: [],
  remark: ''
})

// 预览相关
const previewVisible = ref(false)
const currentRule = ref({})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择异常类型', trigger: 'change' }
  ],
  reminderType: [
    { required: true, message: '请选择提醒类型', trigger: 'change' }
  ],
  timeLimit: [
    { required: true, message: '请设置处理时限', trigger: 'change' }
  ],
  reminderTimes: [
    { required: true, message: '请设置提醒次数', trigger: 'change' }
  ],
  reminderInterval: [
    { required: true, message: '请设置提醒间隔', trigger: 'change' }
  ],
  reminderMethods: [
    { required: true, message: '请选择提醒方式', trigger: 'change' },
    { type: 'array', min: 1, message: '至少选择一种提醒方式', trigger: 'change' }
  ],
  templates: [
    { required: true, message: '请添加提醒模板', trigger: 'change' },
    { type: 'array', min: 1, message: '至少添加一个提醒模板', trigger: 'change' }
  ]
}

// 获取规则列表
const getRuleList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptionReminderRuleList()
    ruleList.value = data
  } catch (error) {
    console.error('获取规则列表失败:', error)
    ElMessage.error('获取规则列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const { data } = await getMerchantRoleList()
    roleList.value = data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 获取通知模板列表
const fetchTemplateList = async () => {
  try {
    const { data } = await getMerchantNoticeTemplateList()
    templateList.value = {
      system: data.filter(t => t.type === 'system'),
      sms: data.filter(t => t.type === 'sms'),
      email: data.filter(t => t.type === 'email'),
      wechat: data.filter(t => t.type === 'wechat')
    }
  } catch (error) {
    console.error('获取通知模板列表失败:', error)
  }
}

// 新建规则
const handleAddRule = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = Array.isArray(form[key]) ? [] : ''
  })
  form.timeLimit = 24
  form.reminderTimes = 3
  form.reminderInterval = 4
  form.reminderMethods = ['system']
  dialogVisible.value = true
}

// 编辑规则
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 复制规则
const handleCopy = async (row) => {
  try {
    await copyMerchantOrderExceptionReminderRule(row.id)
    ElMessage.success('复制成功')
    getRuleList()
  } catch (error) {
    console.error('复制规则失败:', error)
  }
}

// 预览规则
const handlePreview = (row) => {
  currentRule.value = row
  previewVisible.value = true
}

// 删除规则
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该规则吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantOrderExceptionReminderRule(row.id)
    ElMessage.success('删除成功')
    getRuleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除规则失败:', error)
    }
  }
}

// 更新状态
const handleStatusChange = async (row) => {
  try {
    await updateMerchantOrderExceptionReminderRuleStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    row.status = row.status === 1 ? 0 : 1
  }
}

// 添加模板
const handleAddTemplate = () => {
  form.templates.push({
    method: '',
    templateId: ''
  })
}

// 删除模板
const handleRemoveTemplate = (index) => {
  form.templates.splice(index, 1)
}

// 添加升级规则
const handleAddEscalation = () => {
  form.escalationRules.push({
    condition: '',
    target: []
  })
}

// 删除升级规则
const handleRemoveEscalation = (index) => {
  form.escalationRules.splice(index, 1)
}

// 获取模板列表
const getTemplateList = (method) => {
  return templateList.value[method] || []
}

// 获取模板名称
const getTemplateName = (method, templateId) => {
  const template = templateList.value[method]?.find(t => t.id === templateId)
  return template ? template.name : templateId
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addMerchantOrderExceptionReminderRule(form)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantOrderExceptionReminderRule(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getRuleList()
  } catch (error) {
    console.error('保存规则失败:', error)
  }
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    complaint: 'warning',
    product: 'error',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    refund: '退款纠纷',
    complaint: '服务投诉',
    product: '商品问题',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取提醒类型标签类型
const getReminderTypeTag = (type) => {
  const typeMap = {
    time_limit: 'primary',
    approaching: 'warning',
    overtime: 'danger',
    escalation: 'error'
  }
  return typeMap[type] || ''
}

// 获取提醒类型标签文本
const getReminderTypeLabel = (type) => {
  const typeMap = {
    time_limit: '处理时限提醒',
    approaching: '即将超时提醒',
    overtime: '超时提醒',
    escalation: '升级提醒'
  }
  return typeMap[type] || type
}

// 获取通知方式标签类型
const getMethodTag = (method) => {
  const methodMap = {
    system: 'info',
    sms: 'success',
    email: 'warning',
    wechat: 'primary'
  }
  return methodMap[method] || ''
}

// 获取通知方式标签文本
const getMethodLabel = (method) => {
  const methodMap = {
    system: '系统通知',
    sms: '短信通知',
    email: '邮件通知',
    wechat: '微信通知'
  }
  return methodMap[method] || method
}

// 获取升级条件标签文本
const getEscalationConditionLabel = (condition) => {
  const conditionMap = {
    overtime: '超时未处理',
    complaint: '客户投诉',
    repeat: '重复异常',
    amount: '金额较大'
  }
  return conditionMap[condition] || condition
}

// 获取角色名称
const getRoleName = (roleId) => {
  const role = roleList.value.find(r => r.id === roleId)
  return role ? role.name : roleId
}

onMounted(() => {
  getRuleList()
  getRoleList()
  fetchTemplateList()
})
</script>

<style lang="scss" scoped>
.reminder-config {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .rule-list {
    margin-bottom: 20px;
  }

  .template-list {
    .template-item {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      .template-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .template-title {
          font-weight: 500;
        }
      }

      .template-content {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
      }
    }

    .template-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .escalation-list {
    .escalation-item {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      .escalation-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .escalation-title {
          font-weight: 500;
        }
      }

      .escalation-content {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
      }
    }

    .escalation-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .rule-preview {
    .preview-section {
      margin-bottom: 20px;

      h3 {
        margin: 0 0 15px;
        font-size: 16px;
        font-weight: 500;
      }

      .method-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .mx-1 {
          margin: 0 4px;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 